<template>
  <el-cascader
    class="branch-cascader"
    v-model="selectVal"
    :props="props"
    :options="options"
    :style="this.styles"
    :show-all-levels="false"
    :placeholder="placeholder"
    :disabled="disabled||readonly"
    @change="handleChange"
    clearable />
</template>
<script>
import { getPureSonCompanyList } from '@/api/supplier/components';
export default {
  name: 'BranchSelect',
  props: {
    value: { type: [Number, String], },
    disabled: { type: Boolean, default: false },
    readonly: { type: Boolean, default: false },
    placeholder: { type: String, default: '请选择公司名称' },
    styles: { type: Object, default () { return { width: '100%' } } },
  },
  data () {
    return {
      loading: false,
      selectVal: this.value || '',
      options: [],
      optionMap: {},
      visible: false,
      props: {
        checkStrictly: true,
        emitPath: false,
      },
    };
  },
  watch: {
    value: {
      handler (val) {
        if (val) {
          this.selectVal = val;
        }
      },
      immediate: true,
    },
  },
  mounted () {
    this.getRemoteData()
  },
  methods: {
    handleChange (val) {
      // 值回显父组件
      this.$emit('input', val);
      // change事件
      this.$emit('change', val);
      //
      this.$emit('onSelected', this.optionMap[val])
    },
    async getRemoteData () {
      this.loading = true;
      const resp = await getPureSonCompanyList({});
      this.loading = false;
      const generateData = list => {
        return list.map(item => {
          const obj = {
            value: item.organizeCode,
            label: item.organizeName
          }
          this.optionMap[item.organizeCode] = item
          if (item.sonOrganize && item.sonOrganize.length) {
            obj.children = generateData(item.sonOrganize)
          } else {
            obj.leaf = true
          }
          return obj
        })
      }
      if (resp && resp.result && resp.result && resp.result.length) {
        this.options = generateData(resp.result)
      } else {
        this.options = []
      }
    },
    resetSelectVal () {
      this.selectVal = undefined
    },
  }
};
</script>

<style lang="less">
.branch-select-container {
  .input {
    cursor: pointer;
  }
}
.cascader-container {
  min-height: 300px;
}
.el-cascader-panel {
  .el-cascader-menu__wrap {
    overflow-x: auto !important;
  }
}
</style>
<style lang="less" scoped>
.actions {
  padding:  20px 0;
  text-align: center;
}
</style>
